<template>
  <div class="order-container">
    <!-- 搜索框 -->
    <div class="search-container">
      <div class="search-box">
        <text class="search-icon">🔍</text>
        <input
          type="text"
          class="search-input"
          placeholder="请输入买家信息或手机号搜索"
          placeholder-class="placeholder"
          confirm-type="search"
          @blur="searchOrder"
          clearable
        />
      </div>
    </div>

    <!-- 顶部选项卡 -->
    <div class="tab-container">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        class="tab-item"
        :class="{ active: query.order_status === tab.value }"
        @click="switchTab(tab.value)"
      >
        {{ tab.name }}
      </div>
    </div>

    <!-- 订单列表 -->
    <scroll-view
      :style="{ height: windowHeight + 'px' }"
      scroll-y
      @scrolltolower="loadMore"
    >
      <div class="order-list">
        <!-- 时代灯饰订单 -->
        <div
          class="order-item"
          v-for="item in orderList"
          :key="item.id"
          @click="orderDetail(item)"
        >
          <div class="order-header">
            <div class="store-info">
              <div class="store-icon">🏪</div>
              <div class="store-name">{{ item.shop?.name || "" }}</div>
              <view
                class="payment-status"
                :class="[
                  settle_payment_status_list[item?.settle_payment_status]
                    ?.class,
                ]"
              >
                <view class="status-dot"></view>
                <text>{{
                  settle_payment_status_list[item?.settle_payment_status]?.name
                }}</text>
              </view>
            </div>
            <view class="order-toggle-box">
              <div
                :class="`order-status ${
                  tabs.find((tab) => tab.value === item.order_status)?.class
                }`"
              >
                {{
                  tabs.find((tab) => tab.value === item.order_status)?.name ||
                  ""
                }}
              </div>
              <!-- 商品列表展开/收起按钮 -->
              <div
                class="product-toggle"
                @click.stop="item.expanded = !item.expanded"
              >
                <span></span>
                <span
                  class="toggle-icon"
                  :class="{ 'is-expanded': item.expanded }"
                >
                  {{ item.expanded ? "收起" : "展开" }}
                </span>
              </div>
            </view>
          </div>

          <!-- 商品列表 -->
          <div class="product-list" v-show="item.expanded">
            <div
              class="product-item"
              v-for="good in item.order_detail"
              :key="good.id"
            >
              <div class="product-info">
                <div class="product-name">{{ good.product_name }}</div>
                <div class="product-quantity">× {{ good.quantity }}</div>
              </div>
              <div class="product-spec">{{ good.goods_spec_value_name }}</div>
              <div class="product-price">¥ {{ good.total_price }}</div>
            </div>
          </div>
          <!-- 订单总结 -->
          <div class="order-footer">
            <div class="order-total">
              <span>下单时间：{{ item.create_time }}</span>
              <span>
                共{{
                  item.order_detail.reduce(
                    (total, good) => bc(`${total} + ${good.quantity}`),
                    0
                  )
                }}件商品 合计：<span class="order-total-price"
                  >¥
                  {{
                    item.order_detail.reduce(
                      (total, good) => bc(`${total} + ${good.total_price}`),
                      0
                    )
                  }}</span
                >
              </span>
            </div>
            <div class="order-actions-vertical">
              <button
                class="action-btn share-btn"
                @click.stop="shareOrder(item)"
                v-if="
                  item.order_status === 1 && checkRoles('wx_shareOrder', 'btn')
                "
                open-type="share"
              >
                分享订单
              </button>
              <button
                class="action-btn cancel-btn"
                @click.stop="cancelOrderOption(item)"
                v-if="
                  item.order_status < 4 && checkRoles('wx_cancelSingle', 'btn')
                "
              >
                取消
              </button>
              <button
                class="action-btn pay-btn"
                @click.stop="setPayment(item)"
                v-if="
                  [2, 3, 4].includes(item.order_status) &&
                  item.settle_payment_status !== 2 && checkRoles('wx_payment', 'btn')
                "
              >
                结款
              </button>
              <button
                v-if="item.order_status === 2 && checkRoles('wx_send', 'btn')"
                class="action-btn pay-btn"
                @click.stop="sendGoodsOpen(item)"
              >
                发货
              </button>
            </div>
          </div>
        </div>
        <div v-if="orderList.length === 0" class="empty-order">
          <gui-image
            src="https://cdn.duyumy.com/accessory/0fe61301ec884459440a85e2fcd72d1ae98c46da.png"
          ></gui-image>
          <div style="font-size: 28rpx; color: #999; margin-top: -20rpx">
            暂无订单~
          </div>
        </div>
      </div>
    </scroll-view>
    <SendOrder ref="SendOrderRef" @sendGoods="sendGoods" />
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import {
  getOrderList,
  cancelOrder,
  sendGoodsApi,
  setPaymentOrder,
  getKeyforOrder,
} from "@/api/order";
import { onShow, onShareAppMessage } from "@dcloudio/uni-app";
import { bc, showToast } from "@/utils/helper";
import SendOrder from "@/component/sendOrder.vue";
const windowHeight = getApp().globalData.systemInfo.windowHeight;
// 选项卡数据
const tabs = [
  {
    name: "全部",
    value: 0,
    class: "all",
  },
  {
    name: "待确认",
    value: 1,
    class: "nopay",
  },
  {
    name: "待发货",
    value: 2,
    class: "waitSend",
  },
  {
    name: "待收货",
    value: 3,
    class: "waitReceive",
  },
  {
    name: "已完成",
    value: 4,
    class: "success",
  },
  // {
  //   name: "交易关闭",
  //   value: 5,
  //   class: "error",
  // },
  // {
  //   name: "售后中",
  //   value: 6,
  //   class: "refund",
  // },
  {
    name: "订单取消",
    value: 7,
    class: "refund",
  },
];
const settle_payment_status_list = ref({
  1: {
    name: "未结款",
    class: "",
  },
  2: {
    name: "已结款",
    class: "paid",
  },
  3: {
    name: "已退款",
    class: "refund",
  },
});

const cancelOrderOption = (item) => {
  console.log(item);
  uni.showModal({
    title: "提示",
    content: "确定取消订单吗？",
    success: async (res) => {
      if (res.confirm) {
        await cancelOrder({
          id: item.id,
        });
        showToast("取消订单成功");
        refreshDataToMorePage();
      }
    },
  });
};
// 页面页码多的时候刷新更新整个块面，适用于页面数据量大的情况 又得刷新下发数据
const refreshDataToMorePage = async () => {
  let oldPage = query.page;
  query.limit = 10 * query.page;
  query.page = 1;
  const res = await getOrderList(query);
  res.data = res.data.map((item) => ({ ...item, expanded: false }));
  orderList.value = res.data;
  query.page = oldPage;
  query.limit = 10;
};

const setPayment = (item) => {
  uni.showModal({
    title: "提示",
    content: "确定已经收到货款？点击确认后订单将变为已结款状态",
    success: async (res) => {
      if (res.confirm) {
        await setPaymentOrder({ id: item.id });
        showToast("结款成功");
        refreshDataToMorePage();
      }
    },
  });
};
const query = reactive({
  page: 1,
  limit: 10,
  buyer_info: '',
  order_status: 0,
});
// 切换选项卡
const switchTab = (value) => {
  query.order_status = value;
  query.page = 1;
  orderList.value.length = 0;
  getOrderListData();
};
const orderList = ref([]);
const getOrderListData = async (type = "init") => {
  const res = await getOrderList(query);
  res.data = res.data.map((item) => ({ ...item, expanded: false }));
  if (res.data.length === 0) return showToast("没有更多数据了");
  if (type === "init") return (orderList.value = res.data);
  orderList.value = [...orderList.value, ...res.data];
};

const SendOrderRef = ref(null);
const sendGoodsOpen = (item) => {
  SendOrderRef.value.show(item.id);
};
const shareOrderObj = ref({});
const shareOrder = (item) => {
  shareOrderObj.value = {
    id: item.id,
    shop_id: item.shop_id,
  };
};
onShareAppMessage(() => {
  return {
    title: "店铺订单确认", // 分享的标题
    path: `/pagesShop/order/orderInfo?id=${shareOrderObj.value.id}&shop_id=${shareOrderObj.value.shop_id}`, // 分享的页面路径，并携带参数
  };
});

const sendGoods = async (sendInfo) => {
  await sendGoodsApi(sendInfo);
  SendOrderRef.value.close();
  await getOrderListData();
  showToast("发货成功");
};

const loadMore = () => {
  query.page++;
  getOrderListData("more");
};

const orderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/order/supplierOrderInfo?id=${order.id}&shop=${JSON.stringify(
      order.shop
    )}`,
  });
};

const searchOrder = async (e) => {
  query.page = 1;
  query.buyer_info = e.detail.value || ''
  const res = await getKeyforOrder(query);
  res.data = res.data.map((item) => ({ ...item, expanded: false }));
  orderList.value = res.data;
};
onShow(() => {
  getOrderListData();
});
</script>

<style scoped lang="scss">
.search-container {
  padding: 20rpx;
  background-color: #fff;
  .search-box {
    display: flex;
    align-items: center;
    height: 72rpx;
    background-color: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    .search-icon {
      font-size: 32rpx;
      color: #999;
      margin-right: 10rpx;
    }
    .search-input {
      width: 100%;
      height: 72rpx;
      font-size: 28rpx;
      color: #333;
      background-color: transparent;
    }

    .placeholder {
      color: #999;
      font-size: 28rpx;
    }
  }
}

.scroll-view {
  white-space: nowrap;
  width: 100%;
  height: 88rpx;
  background: #fff;

  &::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
  }
}

.order-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 选项卡样式 */
.tab-container {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  // overflow: scroll;
  width: 100%;
  z-index: 10;
}

.tab-item {
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  position: relative;
  white-space: nowrap;
}

.tab-item.active {
  color: #1989fa;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #1989fa;
}

/* 订单列表样式 */
.order-list {
  padding: 20rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid #f5f5f5;
}

.store-info {
  display: flex;
  align-items: center;
}

.store-icon {
  margin-right: 10rpx;
  font-size: 32rpx;
}

.store-name {
  font-size: 28rpx;
  font-weight: bold;
}

.order-status {
  font-size: 24rpx;
}

.order-toggle-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* 商品展开/收起按钮样式 */
  .product-toggle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    font-size: 26rpx;
    color: #666;
    cursor: pointer;
  }

  .toggle-icon {
    color: #1989fa;
    font-size: 24rpx;
    display: flex;
    align-items: center;
  }

  .toggle-icon.is-expanded::after {
    content: "▲";
    font-size: 20rpx;
    margin-left: 6rpx;
  }

  .toggle-icon:not(.is-expanded)::after {
    content: "▼";
    font-size: 20rpx;
    margin-left: 6rpx;
  }
}

/* 商品列表样式 */
.product-list {
  padding: 0 20rpx;
}

.product-item {
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.product-name {
  font-size: 28rpx;
  color: #333;
}

.product-quantity {
  font-size: 28rpx;
  color: #999;
}

.product-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.product-price {
  font-size: 28rpx;
  color: #ff4d4f;
}

/* 订单底部样式 */
.order-footer {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
  padding: 20rpx;
  flex-direction: column;
}

.order-total {
  font-size: 26rpx;
  color: #333;
  text-align: left;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  justify-content: flex-end;
  align-items: flex-end;
  // width: 60%;
}

.order-total-price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 30rpx;
  margin-left: 8rpx;
}

.order-actions-vertical {
  display: flex;
  // flex-direction: column;
  align-items: flex-end;
  // gap: 16rpx;
  width: auto;
}

.action-btn {
  padding: 14rpx 36rpx;
  border-radius: 10rpx;
  font-size: 24rpx;
  border: 1px solid #409eff;
  background-color: #fff;
  color: #409eff;
  min-width: 120rpx;
  text-align: center;
  line-height: 1.4;
  white-space: nowrap;
  margin: 10rpx;
}

.cancel-btn {
  color: #666;
  border-color: #ddd;
  background: #fff;
}

.pay-btn {
  color: #409eff;
  border-color: #409eff;
  background: #fff;
}

.ship-btn {
  color: #409eff;
  border-color: #409eff;
}

.send-container {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 10rpx;
  border-bottom: 1px solid #fff;
}

.send-label {
  position: relative;
  top: -4px;
}

.color {
  background-image: linear-gradient(45deg, #abda75, #008aff) !important;
}

.empty-order {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  flex-direction: column;
}

.payment-status {
  display: flex;
  align-items: center;
  padding: 6rpx 16rpx;
  border-radius: 24rpx;
  background: #f5f5f5;
  font-size: 24rpx;
  color: #999;
  transition: all 0.3s ease;
  margin-left: 10rpx;

  &.paid {
    background: rgba(82, 196, 26, 0.1);
    color: #52c41a;
    margin-left: 10rpx;
  }
  &.refund {
    background: rgb(255 0 0 / 55%);
    color: #dcd5d5;
    margin-left: 10rpx;
    text {
      font-size: 24rpx;
      color: #fff;
    }
  }
  .status-dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background: currentColor;
    margin-right: 8rpx;
  }
}
</style>
